/*
 *2020年11月5日
 *@author:huhu
 */

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.concurrent.LinkedBlockingQueue;

import jxl.write.WriteException;
import jxl.write.Number;
public class Staging_Area {

    static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    // 仓库存储缓存
    private static final LinkedBlockingQueue<Integer> list = new LinkedBlockingQueue<Integer>(5);

    //由于所有生产者共用一个线程生产，所以此方法为临界区，需加锁
    public synchronized static void produce(int id) {
        try{
            list.put(Test.data[Test.producePointer]);//容量达到最大时，自动阻塞。
            out.println("生产者" + id +" 生产一个产品:"+Test.data[Test.producePointer]+"\t");
            out.flush();
            Test.producePointer=(Test.producePointer+1)%Test.data.length;//循环生成count

        } catch (InterruptedException e){
            e.printStackTrace();
        }

    }

    public  void consume(int id,int sum) {
        while(Test.c <Test.max){
            try{
                int d = list.take();//容量为0时，自动阻塞。
//                System.out.println("shuju=="+d+"       n=="+Test.c);
                sum += d ;
                Test.consumePointer++;
//                System.out.println("id=="+id);
                try {
                    Test.sheet.addCell( new Number(id,Test.c /Test.consumerCount,sum));//第1列
                    //此代码在使用py2.py时打开，并将上一行注释掉
//                     Test.sheet.addCell(new Number(id,Test.c +1,sum));
                } catch (WriteException e) {
                    e.printStackTrace();
                }
                out.println("消费者" + id+"消费一个产品: "+d+"\t");
                out.flush();
                Test.c++;

            } catch (InterruptedException e){
                e.printStackTrace();
            }

        }

    }

}